﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading;

namespace UtilsBase
{
    public class UtilsFileHelper
    {

        public static string FILE_UPDATE_NAME = "update";
        public static string FILE_DEVICE_NAME = "device";
        public static string FILE_WEB_NAME = "web";


        static object obj = new object();
        /// <summary>

        /// 读取文本文件

        /// </summary>

        /// <param name="filePath"></param>

        /// <returns></returns>

        public static string readFile(string filePath)
        {
            try
            {
                // string filename = filePath;// getParnetDirectory() + UtilsAppsetting.GetSettings("base:initDir") + "gatewaycode.txt";

                if (!File.Exists(filePath))
                {
                    return "";
                }
                lock (obj)
                {
                    StreamReader srInput = new StreamReader(filePath, Encoding.GetEncoding("utf-8"));
                    StringBuilder sb = new StringBuilder();
                    string line;
                    while ((line = srInput.ReadLine()) != null)//按行读入文本文件
                    {
                        sb.Append(line);
                    }
                    srInput.Close();
                    return sb.ToString();
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
            return "";
        }


        public static string readDeviceCode(string filename)
        {
            string Code = "";
            try
            {
                string filePath = getParnetDirectory() + UtilsAppsetting.GetSettings("base:initDir") + filename;// "gatewaycode.txt";
                                                                                                                // Console.WriteLine("1"+filePath);
                if (File.Exists(filePath))
                {
                    Code = readFile(filePath).ToString();
                }

            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
            return Code;
        }

        /// <summary>
        /// 按每行key:value 读取
        /// </summary>
        /// <param name="filename"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        public static string readDeviceCode(string filename, string key)
        {
            try
            {
                string filePath = getParnetDirectory() + UtilsAppsetting.GetSettings("base:initDir") + filename;// "gatewaycode.txt";      



                // Console.WriteLine("1"+filePath);
                if (File.Exists(filePath))
                {
                    StreamReader srInput = new StreamReader(filePath, Encoding.GetEncoding("utf-8"));
                    string line;
                    while ((line = srInput.ReadLine()) != null)//按行读入文本文件
                    {
                        line = line.Trim();
                        if (line.Contains(key + ":") && !line.Contains("#"))
                        {
                            //#为注释，不会执行到这里
                            srInput.Close();
                            return line.Split(":")[1].Trim();
                        }
                    }
                    srInput.Close();
                }

            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
            return "";
        }




        public static void writeFile(string message, string fileName)
        {

            using (StreamWriter sw = File.CreateText(fileName))
            {
                sw.WriteLine(message);
                sw.Close();//关闭文件
            }
        }
        /// <summary>
        /// 写入日志
        /// </summary>
        /// <param name="service"></param>
        /// <param name="message"></param>
        public void log_WriteMessageAppend(string service, string message)
        {
            if (UtilsAppsetting.GetSettings("base:logSave") == "false")
            {
                return;
            }

            //后期加判断 生产环境不定，其它环境写日志
            try
            {
                message = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss").ToString() + " :" + message;
                string fileName = getParnetDirectory() + UtilsAppsetting.GetSettings("base:logDir") + "/" + service + "_log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
                writeMessageAppend(message, fileName);
            }
            catch (Exception ex)
            {
                Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " log_WriteMessageAppend 文件写入失败");

            }

        }

        public bool updateFile(string fileName, string message)
        {
            using (StreamWriter sw = new StreamWriter(fileName, false))
            {
                sw.WriteLine(message);
                sw.Close();//关闭文件
            }
            return true;
        }
        public string getFile(string filename)
        {
            string content = "";
            try
            {
                if (File.Exists(filename))
                {
                    content = readFile(filename).ToString();
                }
            }
            catch (Exception ex)
            {
                Console.Write(ex);
            }
            return content;
        }
        ///// <summary>
        ///// 设备工作服务
        ///// </summary>
        ///// <param name="message"></param>
        ///// <param name="fileName"></param>
        //public void deviceServer_WriteMessageAppend(string message)
        //{
        //    try
        //    {
        //        string fileName = getParnetDirectory() + UtilsAppsetting.GetSettings("base:logDir") + "/deviceServer_log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
        //        writeMessageAppend(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " " + message, fileName);
        //    }
        //    catch (Exception ex)
        //    {
        //        //  Console.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + " deviceServer_WriteMessageAppend 文件写入失败");
        //        Console.WriteLine(ex);
        //    }

        //}
        ///// <summary>
        ///// 升级服务
        ///// </summary>
        ///// <param name="message"></param>
        ///// <param name="fileName"></param>
        //public void upgradeServer_WriteMessageAppend(string message)
        //{
        //    string fileName = getParnetDirectory() + UtilsAppsetting.GetSettings("base:logDir") + "/upgradeServer_log_" + DateTime.Now.ToString("yyyy-MM-dd") + ".txt";
        //    writeMessageAppend(message, fileName);

        //}
        /// <summary>
        /// 删除日志
        /// </summary>
        public static void fileDel()
        {
            while (true)
            {

                try
                {
                    //删除10天前的日志
                    foreach (string filename in Directory.GetFiles(getParnetDirectory() + UtilsAppsetting.GetSettings("base:logDir")))
                    {
                        Console.WriteLine(filename);
                        if (filename.Split(".").Length >= 1)
                        {
                            //if (DateTime.ParseExact(filename.Split("_")[2].Split(".")[0].ToString(), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture) < DateTime.ParseExact(System.DateTime.Now.AddDays(-2).ToString("yyyy-MM-dd"), "yyyy-MM-dd", System.Globalization.CultureInfo.InvariantCulture))

                            if (Convert.ToDateTime(filename.Substring(filename.Length - 14, 10).ToString()) < DateTime.Now.AddDays(-2))
                            {
                                File.Delete(filename);
                            }
                        }
                    }
                    Console.WriteLine(" 清理日志成功");
                }
                catch (Exception ex) { Console.WriteLine(ex); }

                Thread.Sleep(60 * 60 * 1000);//10小时
            }
        }
        /// <summary>

        /// 写入文件(追加)

        /// </summary>

        /// <param name="message"></param>

        /// <param name="fileName"></param>

        private void writeMessageAppend(string message, string fileName)
        {

            try
            {
                using (StreamWriter sw = new StreamWriter(fileName, true))
                {
                    sw.WriteLine(message);
                    sw.Close();//关闭文件
                }
                //using (TextWriter sw = TextWriter.Synchronized(File.AppendText(fileName)))
                //{
                //    sw.WriteLine(message);
                //    sw.Close();//关闭文件
                //}

            }
            catch (Exception ex)
            {
                //Console.WriteLine(System.DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + fileName+ " writeMessageAppend 文件写入失败");
                Console.WriteLine(ex);
            }
            finally
            {

            }
        }
        public static string getParnetDirectory()
        {
            //Directory.SetCurrentDirectory("../");
            // Console.WriteLine("Directory.GetCurrentDirectory:"+Directory.GetCurrentDirectory() + "/");
            // Console.WriteLine("System.Environment.CurrentDirectory:" + System.Environment.CurrentDirectory + "/");
            return AppDomain.CurrentDomain.BaseDirectory + "/";
            // return System.Environment.CurrentDirectory;
        }

        //public static string getCurrentDirectory()
        //{
        //    var dirpath = Directory.GetCurrentDirectory();
        //    Console.WriteLine("Directory.GetCurrentDirectory = " + dirpath);

        //    // 通过 AppDomain.CurrentDomain.BaseDirectory 读取根目录
        //    var dirpath1 = AppDomain.CurrentDomain.BaseDirectory;
        //    Console.WriteLine("AppDomain.CurrentDomain.BaseDirectory = " + dirpath1);
        //    return dirpath1;
        //    // 通过 Environment.CurrentDirectory 来读取根目录
        //    var dirpath2 = Environment.CurrentDirectory;
        //    Console.WriteLine("Environment.CurrentDirectory = " + dirpath2);

        //    // 通过 Assembly.GetExecutingAssembly().Location 来获取运行程序集所在的位置，从而判断根目录
        //   // var dirpath3 = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
        //   // Console.WriteLine("Path.GetDirectoryName Assembly.GetExecutingAssembly().Location = " + dirpath3);

        //    // 通过 AppContext.BaseDirectory 获取根目录
        //    var dirpath4 = AppContext.BaseDirectory;
        //    Console.WriteLine("AppContext.BaseDirectory = " + dirpath4);
        //}
    }
}
